import { app, shell, BrowserWindow,ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/images/mini_apps_logo.png?asset'
import { InitWindowPool,WindowPoolItem } from "../preload/winPool";
const fs = require('fs');



var mainWindow;
var windowPool; //窗口池

function createWindow(): void {
	// Create the browser window.


	mainWindow = new BrowserWindow({
		width: 960,
		height: 670,
		show: false,
		autoHideMenuBar: true,
		// ...(process.platform === 'linux' ? { icon } : {}),
		icon:icon, //图标
		webPreferences: {
			preload: join(__dirname, '../preload/index.js'),
			sandbox: false,
            webSecurity: false, //关闭安全检查， 允许跨域， 不推荐
			webviewTag:true,
            nodeIntegration: true,
			contextIsolation:false,
			// enableRemoteModule:true,
		},
	})
	
	mainWindow.webContents.openDevTools();//打开调试工具

	mainWindow.on('ready-to-show', () => {
		mainWindow.show()
	})

	mainWindow.webContents.setWindowOpenHandler((details) => {
		shell.openExternal(details.url)
		return { action: 'deny' }
	})

	// HMR for renderer base on electron-vite cli.
	// Load the remote URL for development or the local html file for production.
	if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
		mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
		// if (!process.env.IS_TEST) childWindow.webContents.openDevTools(); // 打开调试工具
	} else {
		mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
	}

	// const filter = { urls: ['*://*/*'] }
	// session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
	// 	details.requestHeaders['Origin'] = '*'
	// 	callback({ cancel: false, requestHeaders: details.requestHeaders })
	// })
	
    /* // 初始化窗口池(加载小程序窗口)
    var windowPool = new InitWindowPool(mainWindow)
	// new InitWindowPool(mainWindow) */

	// 监听 close 事件, 所有窗口都关闭时，窗口池销毁
	mainWindow.on('close', (_event) => {
		var curWinItems:WindowPoolItem[]=[]; // 存活窗口
		// 关闭所有窗口
		for (let i = 0; i < windowPool.winItems.length; i++) {
			if(windowPool.winItems[i].param){
				curWinItems.push(windowPool.winItems[i])
			}
		}
		
		if(curWinItems.length==0){
			//关闭所有窗口
			app.quit()
		}else{
			//窗口是否可见的
			let winShowItem:WindowPoolItem[]=[];
			//判断存活窗口是否都隐藏如果都隐藏就关闭所有的窗口
			curWinItems.forEach(item => {
				if (item.win.isVisible()) {
					//窗口是可见的
					winShowItem.push(item);
				}
			});
			if(winShowItem.length==0){
				//关闭所有窗口
				app.quit()
			}
		}
	});

	/* //禁用F5刷新
    globalShortcut.register('f5', () => {
		console.log('F5 is pressed but refresh is disabled');
        // 不执行mainWindow.reload()
    });
	//禁用快捷键control+r刷新
    globalShortcut.register('CommandOrControl+R', () => {
        console.log('CommandOrControl+R is pressed but refresh is disabled');
        // 不执行mainWindow.reload()
    }); */

}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
	// Set app user model id for windows
	electronApp.setAppUserModelId('com.electron')

	// Default open or close DevTools by F12 in development
	// and ignore CommandOrControl + R in production.
	// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
	app.on('browser-window-created', (_, window) => {
		optimizer.watchWindowShortcuts(window)
	})

	createWindow()

	app.on('activate', function () {
		// On macOS it's common to re-create a window in the app when the
		// dock icon is clicked and there are no other windows open.
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})

	
	//创建apps目录
	createAppDirectory().then(()=>{
	    
	});

	//创建窗口池
	createWindowPool().then(()=>{
	    
	});
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})


// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

//创建apps目录
function createAppDirectory() {
	return new Promise((resolve, _reject) => {
		if(!fs.existsSync('apps/')){
			fs.mkdirSync("apps");
		}
		resolve(true)
	});
}

//创建窗口池
function createWindowPool() {
	return new Promise((resolve, _reject) => {

		// 初始化窗口池(加载小程序窗口)
		windowPool = new InitWindowPool(mainWindow);
		// new InitWindowPool(mainWindow)
		console.log("windowPool")
		mainWindow.webContents.send('window-pool-success');//通知渲染进程，窗口池初始化完成
		resolve(true)
	});
}

//创建项目
ipcMain.on("init-window-pool",(_event)=> {
	
	console.log("windowPool2:")
	if(windowPool.winItems.length > 0){
		console.log("windowPool3")
		mainWindow.webContents.send('window-pool-success');//通知渲染进程，窗口池初始化完成
	}

});
